import loginRequest from "./loginRequest.js";
import $kt from "@/uni_modules/kantboot-framework-uniapp";
import check from './check';

let result = {}

/**
 * 发送成功的消息
 */
result.sendSuccessMsg = (msg) => {
    $kt.event.emit("nextButtonInLogin:success", {"msg": msg});
}

/**
 * 发送失败的消息
 */
result.sendErrorMsg = (errMsg) => {
    $kt.event.emit("nextButtonInLogin:error", {"errMsg": errMsg});
}

result.isHasBack = () => {
    let pages = getCurrentPages();
    if (pages.length > 1) {
        return true;
    }
    return false;
}

/**
 * 登录成功处理
 * @param {object} res
 * @param {object} ktButtonRef
 */
result.loginSuccessHandle = (res) => {
    $kt.request.setToken(res.data.token);
    $kt.userAccount.setSelf(res.data.userAccount);
    $kt.userAccount.setIsLogin(true);
    result.sendSuccessMsg(res.msg);
    // 发送登录成功事件
    $kt.event.emit("login:success");

}

/**
 * 发送验证码
 */
result.sendVerificationCode = (bodyData) => {
    let flag = false;
    if (!bodyData?.to) {
        return new Promise((resolve, reject) => {
            result.sendErrorMsg($kt.i18n.zhToGlobal("未输入电话号码或邮箱"));
            reject();
        });
    }

    return new Promise(async (resolve, reject) => {


        if (bodyData?.methodCode === "phone") {
            if (!bodyData?.phoneAreaCode) {
                result.sendErrorMsg($kt.i18n.zhToGlobal("未选择电话号码区号"));
                reject();
            }

            await check.checkPhone(bodyData?.phoneAreaCode, bodyData?.to).catch(() => {
                result.sendErrorMsg($kt.i18n.zhToGlobal("电话号码格式错误"));
                reject();
                flag = true;
            });
            if (flag) {
                return;
            }
            
            await loginRequest
                .sendLoginVerificationCodeByPhone({
                    phone: bodyData?.to,
                    phoneAreaCode: bodyData?.phoneAreaCode
                })
                .catch((err) => {
                    result.sendErrorMsg(err.errMsg);
                    reject();
                    flag = true;
                });
            if (flag) {
                return;
            }
            resolve();
            return;
        }
        if (bodyData?.methodCode === "email") {
            await check.checkEmail(bodyData?.to).catch(() => {
                reject();
                flag = true;
            });
            await loginRequest
                .sendLoginVerificationCodeByEmail({email: bodyData?.to})
                .catch((err) => {
                    result.sendErrorMsg({errMsg: err.errMsg});
                    reject(err);
                    flag = true;
                });
            if (flag) {
                return;
            }
            resolve();
        }
    });
}


/**
 * 登录
 */
result.login = (bodyData) => {
    let flag = false;
    return new Promise(async (resolve, reject) => {
        if(bodyData?.to==null||!bodyData?.to){
            result.sendErrorMsg($kt.i18n.zhToGlobal("未输入电话号码或邮箱"));
            reject();
            return;
        }
        if (bodyData?.methodCode === "phone") {
            // 校验电话号码
            await check.checkPhone(bodyData?.phoneAreaCode, bodyData?.to).catch(() => {
                result.sendErrorMsg($kt.i18n.zhToGlobal("电话号码格式错误"));
                reject();
                flag = true;
            });
            if (flag) {
                return;
            }
        }
        if (bodyData?.methodCode === "email") {
            // 校验邮箱
            await check.checkEmail(bodyData?.to).catch(() => {
                result.sendErrorMsg($kt.i18n.zhToGlobal("邮箱格式错误"));
                reject();
                flag = true;
            });
            if (flag) {
                return;
            }
        }
        if (bodyData?.typeCode==="password") {
            if (!bodyData?.password) {
                result.sendErrorMsg($kt.i18n.zhToGlobal("未输入密码"));
                reject();
                return;
            }
        }
        if (bodyData?.typeCode==="verificationCode"){
            if (!bodyData?.verificationCode) {
                result.sendErrorMsg($kt.i18n.zhToGlobal("未输入验证码"));
                reject();
                return;
            }
        }
        if (!bodyData?.agree) {
            result.sendErrorMsg($kt.i18n.zhToGlobal("未同意协议"));
            $kt.event.emit("loginPage:selectAgreement:warning");
            reject();
            return;
        }




        if (bodyData?.methodCode === "phone"&&bodyData?.typeCode==="verificationCode") {
            await loginRequest
                .loginByPhoneAndVerificationCode({
                    phone: bodyData?.to,
                    phoneAreaCode: bodyData?.phoneAreaCode,
                    verificationCode: bodyData?.verificationCode,
                })
                .then((res) => {
                    result.loginSuccessHandle(res);
                    resolve();
                })
                .catch((err) => {
                    result.sendErrorMsg(err.errMsg);
                    reject();
                });
            return;
        }

        if (bodyData?.methodCode === "phone"&&bodyData?.typeCode==="password") {
            await loginRequest
                .loginByPhoneAndPassword({
                    phone: bodyData?.to,
                    phoneAreaCode: bodyData?.phoneAreaCode,
                    password: bodyData?.password,
                })
                .then((res) => {
                    result.loginSuccessHandle(res);
                    resolve(res);
                }).catch((err) => {
                    result.sendErrorMsg(err.errMsg);
                    reject(err);
                });
            return;
        }
        if (bodyData?.methodCode === "email"&&bodyData?.typeCode==="verificationCode") {
            await loginRequest
                .loginByEmailAndVerificationCode({
                    email: bodyData?.to,
                    verificationCode: bodyData?.verificationCode,
                })
                .then((res) => {
                    result.loginSuccessHandle(res);
                    resolve();
                }).catch((err) => {
                    result.sendErrorMsg(err.errMsg);
                    reject(err);
                });
            return;
        }
        if (bodyData?.methodCode === "email"&&bodyData?.typeCode==="password") {
            await loginRequest
                .loginByEmailAndPassword({
                    email: bodyData?.to,
                    password: bodyData?.password,
                })
                .then((res) => {
                    console.log(res);
                    result.loginSuccessHandle(res);
                    resolve(res);
                }).catch((err) => {
                    result.sendErrorMsg(err.errMsg);
                    reject(err);
                });
        }
    });
}

export default result;